{
  // 用 Promise 封装一个 ajax
  const promiseAjax = function (data) {
    function formatParams(param) {
      var arr = [];
      for (var name in param) {
        arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(param[name]));
      }
      arr.push(("v=" + Math.random()).replace(".", ""));
      return arr.join("&");
    }
    if (!data) data = {}
    data.params = data.params || {}

    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();

      if (data.type === 'get') {
        data.params = formatParams(data.params); //options.data请求的数据

        xhr.open("GET", data.url + "?" + data.params, true);
        xhr.send(null);
      } else if (options.type == "post") {
        xhr.open("POST", data.url, true);
        xhr.setRequestHeader("Content-type", "application/json");
        xhr.send(data.params);
      }

      xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
          if (xhr.status === 200) {
            resolve(xhr.response)
          } else {
            reject(xhr.responseText);
          }
        }
      }
    })
  }

}

{
  // 实现一个功能，发送请求 5s 时间后，如果没有数据返回，中断请求,提示错误
  /**
   * @param {Object} params 
   */
  const request = (params) => {
    const option = {
      timeOut: 5000,
      ...params
    }
    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest()
      let isTimeOut = false
      const timer = setTimeout(function () {
        isTimeOut = true;
        xhr.abort();
        reject('request is timeout ！！！')
      }, option.timeOut)
      xhr.open("GET", option.url);
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          if (isTimeOut) return;//忽略中止请求
          clearTimeout(timer);//取消等待的超时
          if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
            resolve(xhr.responseText)
          } else {
            reject(`Request was unsuccessful ！！！ ${xhr.status}`)
          }
        }
      }
      // 可以根据不同的请求方法发送数据
      xhr.send(null);
    })
  }

  // 调用
  const getData = async () => {
    const opt = {
      url: 'http://localhost:3000/timeout'
    }
    try {
      const res = await request(opt)
    } catch (error) {
      console.log(error) // request is timeout ！！！
    }
  }

  getData()
}